const std = @import("std");
const maxInt = std.math.maxInt;
const curses = @cImport({
	@cInclude("ncurses.h");
});
const locale = @cImport({
	@cInclude("locale.h");
});

const CellColor = @import("constants.zig").CellColor;
const Game = @import("game.zig").Game;


pub fn main() !void {
	const window: *curses.struct__win_st = setup_curses() orelse {
		const stderr = std.io.getStdErr().writer();
		try stderr.print("Error: Failed to initialize window\n", .{});
		reset_curses();
		return;
	};
	defer reset_curses();


	const levels: [3][]const u8 = .{
		"levels/level1.txt",
		"levels/level2.txt",
		"levels/level3.txt",
	};

	var i: usize = 0;
	while (true) {
		var game = Game{
			.level_path = levels[i],
			.window = window,
		};
		try game.init();
		defer game.deinit();

		try game.main_loop();

		i += 1;
		if (i >= levels.len) {
			i = 0;
		}
	}
}


fn setup_curses() ?*curses.struct__win_st {
	const window: ?*curses.struct__win_st = curses.initscr();
	_ = locale.setlocale(locale.LC_ALL, "");
	_ = curses.cbreak();
	_ = curses.noecho();
	_ = curses.start_color();
	curses.timeout(0);

	_ = curses.init_pair(
		@intFromEnum(CellColor.NORMAL),
		0xf0,
		curses.COLOR_BLACK
	);
	_ = curses.init_pair(
		@intFromEnum(CellColor.HOVERED),
		0xf0,
		curses.COLOR_BLUE
	);
	_ = curses.init_pair(
		@intFromEnum(CellColor.PIPE_NORMAL),
		curses.COLOR_WHITE,
		curses.COLOR_BLACK
	);
	_ = curses.init_pair(
		@intFromEnum(CellColor.PIPE_HOVERED),
		curses.COLOR_WHITE,
		curses.COLOR_BLUE
	);
	_ = curses.init_pair(
		@intFromEnum(CellColor.PIPE_SELECTED),
		curses.COLOR_WHITE,
		curses.COLOR_RED
	);
	_ = curses.init_pair(
		@intFromEnum(CellColor.PIPE_FILLED),
		curses.COLOR_BLUE,
		curses.COLOR_BLACK
	);
	_ = curses.init_pair(
		@intFromEnum(CellColor.PIPE_END),
		0x19,
		curses.COLOR_BLACK
	);
	_ = curses.attron(curses.COLOR_PAIR(1));

	return window;
}


fn reset_curses() void {
	curses.timeout(-1);
	_ = curses.nocbreak();
	_ = curses.echo();
	_ = curses.endwin();
}


test "run tests" {
	_ = @import("tests/main.zig");
}
